﻿using Slave;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace debugFloat
{
    internal class Program
    {
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct mydata
        {
            public float d1;

            public ushort d2;

            public byte d3;
        }

        public static object struct_decode<T>(byte[] buffer,int offsize) where T : struct
        {
            if (buffer == null)
            {
                return null;
            }
            Type genericType = typeof(T);

            int num = Marshal.SizeOf(genericType);

            if (num > buffer.Length)
            {
                return null;
            }

            IntPtr intPtr = Marshal.AllocHGlobal(num);
            object result;
            try
            {
                Marshal.Copy(buffer, offsize, intPtr, num);
                object obj = Marshal.PtrToStructure(intPtr, genericType);
                result = obj;
            }
            catch (Exception)
            {
                result = null;
            }
            finally
            {
                Marshal.FreeHGlobal(intPtr);
            }
            return result;
        }

        static void Main(string[] args)
        {
            Single a = 1.23f;
            byte[] aByte = Transform.ToBytes(a);
            Console.Write("Single 1.23 to bytes :"+Transform.ToHexString(aByte)+"\r\n");

            byte[] bByte = { 0x11, 0x22, 0x33, 0x44 };
            Single b = Transform.ToSingle(bByte);
            Console.Write("Bytes 0x44332211 to single:"+b.ToString()+"\r\n");


            double c = 3.21;
            byte[] cByte = Transform.ToBytes(c);
            Console.Write("Double 3.21 to bytes :" + Transform.ToHexString(cByte) + "\r\n");

            byte[] dByte = { 0x44, 0x22, 0x33, 0x44, 0x44, 0x22, 0x33, 0x44 };
            double d = Transform.ToDouble(dByte);
            Console.Write("Bytes 0x4422334444223344 to double:" + d.ToString() + "\r\n");

            testCom();

            Console.ReadKey();
        }

        static void testCom()
        { 
            SerialPort sp=new SerialPort("COM26",115200,Parity.None,8,StopBits.One);
            sp.Open();
            Console.WriteLine("串口打开！！");
            while (sp.BytesToRead < 7)
            { }
            byte[] b = new byte[7];
            sp.Read(b,0,7);
            Console.WriteLine(Transform.ToHexString(b));
            mydata md = (mydata)struct_decode<mydata>(b,0);
            Console.WriteLine(md.d1.ToString());
            Console.WriteLine(md.d2.ToString());
            Console.WriteLine(md.d3.ToString());
            sp.Close();
            Console.WriteLine("串口关闭！！");

        }
    }
}
